﻿public class Solution {
    public int[] NextGreaterElements(int[] nums)
    {
        // 存储结果
        int[] result = new int[nums.Length];
        Array.Fill(result, -1);
        
        // 单调栈问题
        Stack<int> stack = new Stack<int>();
        for (int i = 0; i < 2 * nums.Length; i++)
        {
            int j = i % nums.Length; // 真正使用的索引

            while (stack.Count > 0)
            {
                int top = stack.Peek();
                if (nums[top] < nums[j])
                {
                    stack.Pop();
                    result[top] = nums[j];
                }
                else break;
            }
            stack.Push(j);
        }
        return result;
    }

    public static void Main(string[] args)
    {
        int[] nums = [1, 2, 3, 4, 3];
        Solution solution = new Solution();
        int[] result = solution.NextGreaterElements(nums);

        foreach (int res in result)
        {
            Console.Write($"{res} ");
        }
        Console.WriteLine();
    }
}